package com.qmx.launcher.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.qmx.launcher.QMXApplication;
import com.qmx.launcher.R;
import com.qmx.launcher.activity.base.BaseActivity;
import com.qmx.launcher.bean.ConfigInfo;
import com.qmx.launcher.callback.JsonCallback;
import com.qmx.launcher.constant.AppConstant;
import com.qmx.launcher.constant.ComParamContact;
import com.qmx.launcher.token.TokenManager;
import com.qmx.launcher.utils.SocketUtil;
import com.qmx.launcher.view.DlgMgr;
import com.qmx.launcher.view.DrawBoardView;
import com.qmx.launcher.view.RadioGroupDialog;
import com.tencent.ilivesdk.ILiveCallBack;
import com.tencent.ilivesdk.ILiveConstants;
import com.tencent.ilivesdk.ILiveSDK;
import com.tencent.ilivesdk.core.ILivePushOption;
import com.tencent.ilivesdk.core.ILiveRoomManager;
import com.tencent.ilivesdk.core.ILiveRoomOption;
import com.tencent.ilivesdk.data.ILivePushRes;
import com.tencent.ilivesdk.data.ILivePushUrl;
import com.tencent.ilivesdk.listener.ILiveEventHandler;
import com.tencent.ilivesdk.view.AVRootView;
import com.tencent.ilivesdk.view.AVVideoView;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * Created by tencent on 2018/5/21.
 */
public class TeachLiveRoomActivity extends Activity implements View.OnClickListener, ILiveRoomOption.onExceptionListener, ILiveRoomOption.onRoomDisconnectListener, SocketUtil.SocketDataCallback {
    private final static String TAG = "RoomActivity";
    private AVRootView avRootView;
    private TextView tvRoomId;
    private ImageView ivSwitch, ivMic, ivLog;
    private int roomId = 0;
    private String isOpen = "0";//1：允许 0：静音
    private String muteType = "1";//1：允许.. 2:禁止.. \参会者自己解除静音
    private String uId = "";//要踢的用户ID
    private LinkedHashMap hashMap = new LinkedHashMap();

    LinearLayout ll_control;
    private boolean bFirstBackPress = true;
    private boolean bFrontCamera = true, bMicEnable = true, bLogEnable = false;
    private ImageView iv_chat, iv_mic, iv_role, iv_log, iv_feedback;
    private DrawBoardView white_board;
    private RelativeLayout rl_white_board_layout;
    public SharedPreferences sharedPreferences;
    public SharedPreferences.Editor editor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SocketUtil.getInstance();
        SocketUtil.getInstance().setSocketDataCallback(this);
        // 初始化UI
        initView();
        // 添加事件监听回调
        ILiveSDK.getInstance().addEventHandler(eventHandler);
    }

    private Context getContext() {
        return isFinishing() ? null : this;
    }

    //////////////////////////////////    TRTC主要流程   ////////////////////////////////////////

    /**
     * 加入音视频房间
     */
    private void enterTrtcRoom(int roomId) {
        // Step 3: 设置渲染控件
        ILiveRoomManager.getInstance().initAvRootView(avRootView);
        customRootView(avRootView);     // 定制渲染控件
        // Step 4: 加入音视频房间
        ILiveRoomOption option = new ILiveRoomOption()
                .imsupport(false)       // 不需要IM功能
                .exceptionListener(this)  // 监听异常事件处理
                .roomDisconnectListener(this)   // 监听房间中断事件
                .controlRole("ed960")  // 使用user角色
                .autoCamera(true)       // 进房间后不需要打开摄像头
                .autoMic(true);         // 进房间后不需打开Mic
        // Step 4: 加入音视频房间
        if (roomId == sharedPreferences.getInt(AppConstant.ROOM_ID, 0)) {
            ILiveRoomManager.getInstance().createRoom(roomId, option);
            Log.i("enterTrtcRoom", "创建房间");
        } else {
            ILiveRoomManager.getInstance().joinRoom(roomId, option);
            Log.i("enterTrtcRoom", "加入房间");
        }
    }

    /**
     * 手动开启推流和录制
     *
     * @param bRecord
     */
    private void startPush(boolean bRecord) {
        ILivePushOption.RecordFileType recordFileType = bRecord ?
                ILivePushOption.RecordFileType.RECORD_HLS_FLV_MP4 : ILivePushOption.RecordFileType.NONE;
        ILivePushOption option = new ILivePushOption()
                .encode(ILivePushOption.Encode.HLS_AND_RTMP)         // 旁路直播协议类型
                .setRecordFileType(recordFileType);      // 录制文件格式
        //手动推流自动录制时，如果需要后台识别特定的录制文件，用户可以通过这个字段做区分。
        // (使用这个字段时，控制台的“自动旁路直播”开关必须关闭)
        //                .setRecordId(123456);
        ILiveRoomManager.getInstance().startPushStream(option, new ILiveCallBack<ILivePushRes>() {
            @Override
            public void onSuccess(ILivePushRes data) {
                if (null != data.getUrls()) {
                    // 遍历推流类型及地址
                    for (ILivePushUrl url : data.getUrls()) {
                        // 处理播放地址
                        Log.i("startPush", "播放地址" + url.getUrl());
                    }
                }
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                // 处理推流失败
                Log.i("startPush", "推流失败原因" + errCode);
            }
        });
    }

    /**
     * 停止手动推流和录制
     */
    private void stopPush() {
        ILiveRoomManager.getInstance().stopPushStream(0, // 直播码模式下填0即可
                new ILiveCallBack() {
                    @Override
                    public void onSuccess(Object data) {
                        // 停止成功
                    }

                    @Override
                    public void onError(String module, int errCode, String errMsg) {
                        // 停止失败
                    }
                });
    }

    /**
     * 处理TRTC 事件
     */
    private ILiveEventHandler eventHandler = new ILiveEventHandler() {
        @Override
        public void onForceOffline(String userId, String module, int errCode, String errMsg) {
            DlgMgr.showMsg(getContext(), "帐号被踢下线: " + module + "|" + errCode + "|" + errMsg);
            finish();
        }

        @Override
        public void onCreateRoomSuccess(int roomId, String groupId) {
            DlgMgr.showToast(getContext(), "创建房间成功");
            startPush(true);
        }

        @Override
        public void onCreateRoomFailed(int roomId, String module, int errCode, String errMsg) {
            DlgMgr.showMsg(getContext(), "创建房间失败: " + module + "|" + errCode + "|" + errMsg);
        }

        @Override
        public void onJoinRoomSuccess(int roomId, String groupId) {
            DlgMgr.showToast(getContext(), "加入房间成功");
        }

        @Override
        public void onJoinRoomFailed(int roomId, String module, int errCode, String errMsg) {
            if (module.equals(ILiveConstants.Module_IMSDK) && (10010 == errCode || 10015 == errCode)) {
                ILiveRoomManager.getInstance().createRoom(roomId, new ILiveRoomOption()
                        .controlRole("user"));
            } else {
                DlgMgr.showMsg(getContext(), "加入房间失败: " + module + "|" + errCode + "|" + errMsg);
            }
        }

        @Override
        public void onQuitRoomSuccess(int roomId, String groupId) {
            finish();
        }

        @Override
        public void onQuitRoomFailed(int roomId, String module, int errCode, String errMsg) {
            DlgMgr.showMsg(getContext(), "退出房间失败: " + module + "|" + errCode + "|" + errMsg);
        }
    };

    //////////////////////////////////    UI处理   ////////////////////////////////////////

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        if (null != intent) {
            roomId = intent.getIntExtra("roomId", 0);
            if (0 != roomId) {
                enterTrtcRoom(roomId);
                timer.start();
                tvRoomId.setText("" + roomId);
            }
        }
    }

    //    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i("onKeyDown==", keyCode + "");
        if (ll_control.getVisibility() == View.INVISIBLE) {
            if (keyCode == KeyEvent.KEYCODE_ALT_LEFT || keyCode == KeyEvent.KEYCODE_ALT_RIGHT) {
                //            timer.cancel();
                //            timer.start();
                Log.i("KEYCODE_ALT_LEFT==", keyCode + "");
                return true;
            }
        }
        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && ll_control.getVisibility() == View.VISIBLE) {
            Log.i("getVisibility==", keyCode + "");
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
            if (ll_control.getVisibility() == View.INVISIBLE) {
                ll_control.setVisibility(View.VISIBLE);
                avRootView.setFocusable(false);
                ll_control.setFocusable(true);
                if (rl_white_board_layout.getVisibility() == View.VISIBLE) {
                    ll_control.setNextFocusForwardId(R.id.ll_white_broad);
                    iv_log.setFocusable(true);
                } else {
                    ll_control.setNextFocusForwardId(R.id.ll_layout);
                }
                timer.start();
                Log.i("INVISIBLE==", keyCode + "");
            } else {
                ll_control.setVisibility(View.INVISIBLE);
                avRootView.setFocusable(true);
                ll_control.setNextFocusForwardId(R.id.av_root_view);
                ll_control.setFocusable(false);
            }
            Log.i("KEYCODE_DPAD_CENTER==", keyCode + "");
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPush();
        ILiveSDK.getInstance().clearEventHandler();
        ILiveRoomManager.getInstance().quitRoom();
    }

    @Override
    public void onBackPressed() {
        if (bFirstBackPress) {
            bFirstBackPress = false;
            //            ILiveRoomManager.getInstance().quitRoom();
        } else {
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        Log.i("onClick", v.getId() + "");
        if (v.getId() == R.id.iv_layout) {
//            showToast("测试遥控器");
            ll_control.setVisibility(View.INVISIBLE);
            avRootView.setFocusable(true);
            ll_control.setNextFocusForwardId(R.id.av_root_view);
            ll_control.setFocusable(false);
            //            bFrontCamera = !bFrontCamera;
            //            ILiveRoomManager.getInstance().switchCamera(bFrontCamera ? ILiveConstants.FRONT_CAMERA : ILiveConstants.BACK_CAMERA);
            //            ivSwitch.setImageResource(bFrontCamera ? R.mipmap.camera : R.mipmap.camera2);
        } else if (v.getId() == R.id.iv_record) {
            bMicEnable = !bMicEnable;
//            showToast("ll_voice");
            ILiveRoomManager.getInstance().enableMic(bMicEnable);
            ivMic.setImageResource(bMicEnable ? R.mipmap.mic : R.mipmap.mic2);
        } else if (v.getId() == R.id.iv_white_broad) {
//            showToast("iv_log");
            if (rl_white_board_layout.getVisibility() == View.INVISIBLE) {
                rl_white_board_layout.setVisibility(View.VISIBLE);
                ll_control.setVisibility(View.INVISIBLE);
                avRootView.setFocusable(true);
                ll_control.setNextFocusForwardId(R.id.av_root_view);
                ll_control.setFocusable(false);
                timer.start();
            } else {
                rl_white_board_layout.setVisibility(View.INVISIBLE);
                timer.start();
            }
        }
    }

    private LinearLayout initClickableLayout(int resId) {
        LinearLayout layout = (LinearLayout) findViewById(resId);
        layout.setOnClickListener(this);
        return layout;
    }

    private void initView() {
        setContentView(R.layout.teach_live_room_activity);
        sharedPreferences = getSharedPreferences(QMXApplication.getInstance().getPackageName(), Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        avRootView = (AVRootView) findViewById(R.id.av_root_view);
        tvRoomId = (TextView) findViewById(R.id.tv_room_id);
        initClickableLayout(R.id.ll_layout);
        initClickableLayout(R.id.ll_record);
        initClickableLayout(R.id.ll_white_broad);
        initClickableLayout(R.id.ll_iv_yun_file);
        initClickableLayout(R.id.ll_close_voice);
        ll_control = initClickableLayout(R.id.ll_control);
        ivMic = (ImageView) findViewById(R.id.iv_record);
        ivLog = (ImageView) findViewById(R.id.iv_white_broad);


        iv_chat = findViewById(R.id.iv_layout);
        iv_chat.setOnClickListener(this);
        iv_mic = findViewById(R.id.iv_record);
        iv_mic.setOnClickListener(this);
        iv_role = findViewById(R.id.iv_yun_file);
        iv_role.setOnClickListener(this);
        iv_log = findViewById(R.id.iv_white_broad);
        iv_log.setOnClickListener(this);
        iv_feedback = findViewById(R.id.iv_close_voice);
        iv_feedback.setOnClickListener(this);


        //        ll_color_list = (LinearLayout) findViewById(R.id.ll_color_list);

        rl_white_board_layout = findViewById(R.id.rl_white_board_layout);
        rl_white_board_layout.setVisibility(View.INVISIBLE);

        white_board = findViewById(R.id.white_board);
        //        white_board.setShowToolsbar(this);

        //        radio_group_colors = findViewById(R.id.radio_group_colors);
        //        //        radio_group_colors.setOnCheckedChangeListener(this);
        //        rg_paint_tools = findViewById(R.id.rg_paint_tools);
        //        //        rg_paint_tools.setOnCheckedChangeListener(this);
        white_board.paint.setXfermode(null);        //取消擦除效果
        white_board.paint.setStrokeWidth(5);        //初始化画笔的宽度


    }

    CountDownTimer timer = new CountDownTimer(5000, 10) {
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            //            rl_top_control.setVisibility(View.INVISIBLE);
            ll_control.setVisibility(View.INVISIBLE);
            avRootView.setFocusable(true);
            ll_control.setNextFocusForwardId(R.id.av_root_view);
            ll_control.setFocusable(false);
        }
    };
    //////////////////////////////////    渲染定制   ////////////////////////////////////////

    private void customRootView(final AVRootView rootView) {

        rootView.setGravity(AVRootView.LAYOUT_GRAVITY_RIGHT);     // 右侧展示小窗口
        rootView.setBackground(R.mipmap.com_bg);                  // 设置背景图片
        rootView.setDeviceRotation(270);

        rootView.setLocalRotationFix(90);
        rootView.setRemoteRotationFix(180);
        //        rootView.setLocalRotationFix(0);
        //        rootView.setRemoteRotationFix(0);

        rootView.setLocalFullScreen(true);
        //        rootView.setAutoOrientation(true);
        //        rootView.setReRotationResize(true);
        rootView.setSubCreatedListener(new AVRootView.onSubViewCreatedListener() {
            @Override
            public void onSubViewCreated() {
                for (int i = 0; i < ILiveConstants.MAX_AV_VIDEO_NUM; i++) {
                    final int index = i;
                    final AVVideoView videoView = rootView.getViewByIndex(i);
                    videoView.setIsPC(true);
                    if (i != 0) {
                        videoView.setDragable(true);
                    } else {

                    }
                    // 可拖动
                    videoView.setGestureListener(new GestureDetector.SimpleOnGestureListener() {
                        @Override
                        public boolean onSingleTapConfirmed(MotionEvent e) {        // 小屏点击交换
                            if (index == 0) {
                            } else {
                                rootView.swapVideoView(0, index);
                            }
                            return super.onSingleTapConfirmed(e);
                        }
                    });
                }
            }
        });
    }

    private AlertDialog inputDlg;

    private void showInputDialog() {
        if (null != inputDlg && inputDlg.isShowing()) {
            inputDlg.dismiss();
            inputDlg = null;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.full_dlg);
        builder.setTitle(R.string.str_problem_other);

        final EditText input = new EditText(getContext());
        input.setSingleLine(false);
        input.setTextColor(Color.BLACK);
        builder.setView(input);

        builder.setPositiveButton("提交", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        inputDlg = builder.create();
        inputDlg.setCanceledOnTouchOutside(true);
        inputDlg.show();
    }

    @Override
    public void onException(int exceptionId, int errCode, String errMsg) {

    }

    @Override
    public void onRoomDisconnect(int errCode, String errMsg) {

    }

    @Override
    public void socketDataCallback(int code, JSONObject str) {
        switch (code) {
            case AppConstant.MESSAGE_EVENT_ID_USER_CAMERA_OPEN:
                userEnableCamera(ILiveRoomManager.getInstance().getActiveCameraId(), true);
                break;
            case AppConstant.MESSAGE_EVENT_ID_USER_CAMERA_CLOSE:
                userEnableCamera(ILiveRoomManager.getInstance().getActiveCameraId(), false);
                break;
            case AppConstant.MESSAGE_EVENT_ID_USER_MIC_OPEN:
                userEnableMic(true);
                break;
            case AppConstant.MESSAGE_EVENT_ID_USER_MIC_CLOSE:
                userEnableMic(false);
                break;
            case AppConstant.MESSAGE_EVENT_ID_USER_ALL_MUTE_1:
                Log.i("USER_ALL_MUTE_1==", code + "");
                break;
            case AppConstant.MESSAGE_EVENT_ID_USER_ALL_MUTE_2:
                Log.i("USER_ALL_MUTE_2==", code + "");
                break;
            case AppConstant.MESSAGE_EVENT_ID_MEETING_ROLLCALL_RECEIVE:
                Log.i("MEETING_ROLLCALL_RE", code + "");
                break;
        }
    }

    // 摄像头
    public void userEnableCamera(int cameraId, boolean enable) {
        ILiveRoomManager.getInstance().enableCamera(cameraId, enable);
    }

    // 麦克风
    public void userEnableMic(boolean enable) {
        ILiveRoomManager.getInstance().enableMic(enable);
    }

    /**
     * 会议室缓存信息
     */
    public void infoMeeting() {
        OkGo.<String>post(AppConstant.Url + ComParamContact.Info.PATH)
                .params(ComParamContact.Info.TOKEN, TokenManager.getInstance().getAuthModel().getToken())
                .params(ComParamContact.Info.ROOM_ID, roomId)
                .execute(new JsonCallback<String>() {

                    @Override
                    public void onSuccess(Response<String> response) {

                    }

                    @Override
                    public void onError(Response<String> response) {
                        Log.i("onError", response.getException().getMessage());
                    }
                });
    }

    /**
     * 开启/关闭语音
     */
    public void meetingCamera() {
        hashMap.put("type", isOpen);
        hashMap.put("uid", uId);
        hashMap.put("room_id", roomId);
        SocketUtil.getInstance().sendSocketData("meeting@camera", hashMap);
        hashMap.clear();
    }

    /**
     * 主持人发起点名
     */
    public void hostCallNames() {
        hashMap.put("room_id", roomId);
        SocketUtil.getInstance().sendSocketData("meeting@rollcall", hashMap);
        hashMap.clear();
    }

    /**
     * 会议人员确认签到
     */
    public void meetingRemain() {
        hashMap.put("room_id", roomId);
        SocketUtil.getInstance().sendSocketData("meeting@remain", hashMap);
        hashMap.clear();
    }

    /**
     * 分享白板事件
     * #0:关闭画板, 1:打开画板, 2:发送画板数据
     */
    public void shareWhiteboard(String mType, String mWhiteboard) {
        hashMap.put("room_id", roomId);
        hashMap.put("type", mType);// 0|1|2, #0:关闭画板, 1:打开画板, 2:发送画板数据
        hashMap.put("data", mWhiteboard);//画板数据  //可选
        SocketUtil.getInstance().sendSocketData("share@whiteboard", hashMap);
        hashMap.clear();
    }

    /**
     * 分享图片事件
     * 'type' => 0|1|2, #0:关闭图片分享, 1:打开图片分享（此功能已转服务端）, 2:操作左右轮播事件
     * 'data' => null  #当type=1 传递图片元数据 | type=2 传递左右录播手势数据
     */
    public void shareImages(String mType, String shareImages) {
        hashMap.put("room_id", roomId);
        hashMap.put("type", mType);// 0|1|2, 0:关闭图片分享, 1:打开图片分享（此功能已转服务端）, 2:操作左右轮播事件
        hashMap.put("data", shareImages);//当type=1 传递图片元数据 | type=2 传递左右录播手势数据
        SocketUtil.getInstance().sendSocketData("share@images", hashMap);
        hashMap.clear();
    }

    /**
     * 主持人授权开麦
     */
    public void meetingMichael() {
        hashMap.put("room_id", roomId);
        hashMap.put("uid", sharedPreferences.getString(AppConstant.USER_ID, ""));
        hashMap.put("type", isOpen);
        SocketUtil.getInstance().sendSocketData("meeting@michael", hashMap);
        hashMap.clear();
    }

    /**
     * 开启/关闭语音
     */
    public void meetingMic() {
        hashMap.put("room_id", roomId);
        hashMap.put("type", isOpen);
        SocketUtil.getInstance().sendSocketData("meeting@mic", hashMap);
        hashMap.clear();
    }

    /**
     * 主持人发起全体静音
     */
    public void meetingMute() {
        hashMap.put("room_id", roomId);
        hashMap.put("type", muteType);
        SocketUtil.getInstance().sendSocketData("meeting@mute", hashMap);
        hashMap.clear();
    }

    /**
     * 主持踢人
     */
    public void meetingKick(String uId) {
        hashMap.put("room_id", roomId);
        hashMap.put("uid", uId);
        SocketUtil.getInstance().sendSocketData("meeting@kick", hashMap);
        hashMap.clear();
    }

    /**
     * 离开会议房间组
     */
    public void meetingLeave() {
        hashMap.put("room_id", roomId);
        SocketUtil.getInstance().sendSocketData("meeting@leave", hashMap);
        hashMap.clear();
    }

    /**
     * 销毁当前会议组
     */
    public void meetingDestroy() {
        hashMap.put("room_id", roomId);
        SocketUtil.getInstance().sendSocketData("meeting@destroy", hashMap);
        hashMap.clear();
    }

    /**
     * 申请主持人
     */
    public void meetingRoot() {
        hashMap.put("room_id", roomId);
        hashMap.put("password", "");
        SocketUtil.getInstance().sendSocketData("meeting@root", hashMap);
        hashMap.clear();
    }

    /**
     * 同步房间信息
     */
    public void meetingInfo() {
        hashMap.put("room_id", roomId);
        SocketUtil.getInstance().sendSocketData("meeting@info", hashMap);
        hashMap.clear();
    }

    /**
     * 当前主持人同意换位
     */
    public void meetingChange() {
        hashMap.put("room_id", roomId);
        hashMap.put("uid", uId);
        SocketUtil.getInstance().sendSocketData("meeting@change", hashMap);
        hashMap.clear();
    }


}
